package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import server.demo.dto.ApiResponse;
import server.demo.entity.Equipment;
import server.demo.service.EquipmentService;

import jakarta.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1/equipment")
public class EquipmentController {
    
    @Autowired
    private EquipmentService equipmentService;
    
    @GetMapping
    public ResponseEntity<ApiResponse<List<Equipment>>> getAllEquipment() {
        try {
            List<Equipment> equipment = equipmentService.getAllEquipment();
            return ResponseEntity.ok(ApiResponse.success(equipment));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取设备列表失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Equipment>> getEquipmentById(@PathVariable Long id) {
        try {
            Optional<Equipment> equipment = equipmentService.getEquipmentById(id);
            if (equipment.isPresent()) {
                return ResponseEntity.ok(ApiResponse.success(equipment.get()));
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取设备详情失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/available")
    public ResponseEntity<ApiResponse<List<Equipment>>> getAvailableEquipment() {
        try {
            List<Equipment> equipment = equipmentService.getAvailableEquipment();
            return ResponseEntity.ok(ApiResponse.success(equipment));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取可用设备失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<Equipment>>> searchEquipment(@RequestParam String keyword) {
        try {
            List<Equipment> equipment = equipmentService.searchEquipmentByName(keyword);
            return ResponseEntity.ok(ApiResponse.success(equipment));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("搜索设备失败：" + e.getMessage()));
        }
    }
    
    @PostMapping
    public ResponseEntity<ApiResponse<Equipment>> createEquipment(@Valid @RequestBody Equipment equipment) {
        try {
            Equipment savedEquipment = equipmentService.saveEquipment(equipment);
            return ResponseEntity.ok(ApiResponse.success(savedEquipment));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("创建设备失败：" + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Equipment>> updateEquipment(@PathVariable Long id, @Valid @RequestBody Equipment equipment) {
        try {
            equipment.setId(id);
            Equipment updatedEquipment = equipmentService.saveEquipment(equipment);
            return ResponseEntity.ok(ApiResponse.success(updatedEquipment));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("更新设备失败：" + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}/status")
    public ResponseEntity<ApiResponse<Equipment>> updateEquipmentStatus(@PathVariable Long id, @RequestBody Map<String, String> statusMap) {
        try {
            Equipment.EquipmentStatus status = Equipment.EquipmentStatus.valueOf(statusMap.get("status"));
            Equipment updatedEquipment = equipmentService.updateEquipmentStatus(id, status);
            return ResponseEntity.ok(ApiResponse.success(updatedEquipment));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("更新设备状态失败：" + e.getMessage()));
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteEquipment(@PathVariable Long id) {
        try {
            equipmentService.deleteEquipment(id);
            return ResponseEntity.ok(ApiResponse.success("删除设备成功", null));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("删除设备失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/statistics")
    public ResponseEntity<ApiResponse<Map<String, Long>>> getEquipmentStatistics() {
        try {
            Map<String, Long> statistics = new HashMap<>();
            statistics.put("total", equipmentService.getAllEquipment().size() + 0L);
            statistics.put("available", equipmentService.getEquipmentCountByStatus(Equipment.EquipmentStatus.AVAILABLE));
            statistics.put("rented", equipmentService.getEquipmentCountByStatus(Equipment.EquipmentStatus.RENTED));
            statistics.put("maintenance", equipmentService.getEquipmentCountByStatus(Equipment.EquipmentStatus.MAINTENANCE));
            return ResponseEntity.ok(ApiResponse.success(statistics));
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                .body(ApiResponse.error("获取设备统计失败：" + e.getMessage()));
        }
    }
}